package com.zhongshengnetwork.rightbe.lang.view;

import android.content.DialogInterface;
import android.content.res.Configuration;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.provider.ContactsContract;
//import android.support.annotation.NonNull;
//import android.support.v4.app.Fragment;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;

import com.bumptech.glide.Glide;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.constant.RefreshState;
import com.scwang.smartrefresh.layout.constant.SpinnerStyle;
import com.scwang.smartrefresh.layout.footer.ClassicsFooter;
import com.scwang.smartrefresh.layout.header.BezierRadarHeader;
import com.scwang.smartrefresh.layout.listener.OnLoadMoreListener;
import com.scwang.smartrefresh.layout.listener.OnRefreshListener;
import com.wang.avi.AVLoadingIndicatorView;
import com.zhongshengnetwork.rightbe.Constant.APIKey;
import com.zhongshengnetwork.rightbe.CustomApplication;
import com.zhongshengnetwork.rightbe.R;
import com.zhongshengnetwork.rightbe.common.AppThemeUtils;
import com.zhongshengnetwork.rightbe.common.BaseAnalyticsFragment;
import com.zhongshengnetwork.rightbe.common.CommonUtils;
import com.zhongshengnetwork.rightbe.common.GsonTools;
import com.zhongshengnetwork.rightbe.common.ScreenUtils;
import com.zhongshengnetwork.rightbe.common.customview.CustomDialog;
import com.zhongshengnetwork.rightbe.common.pulluprefresh.xlistview.XListView;
import com.zhongshengnetwork.rightbe.gsonmodel.CommonModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangHonorModel;
import com.zhongshengnetwork.rightbe.gsonmodel.LangInfoModel;
import com.zhongshengnetwork.rightbe.https.ApiUtils;
import com.zhongshengnetwork.rightbe.https.HttpCallBack;
import com.zhongshengnetwork.rightbe.https.HttpsUtils;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

/**
 * Created by luojingxing on 2018/6/17.
 */

public class HonorLangFragment extends BaseAnalyticsFragment {
    private final int linecount = 4;
    public String userid = null;
    private int pageindex = 0;
    private static final int Records = 20;
    private boolean isHasMore = false;
    private List<LangHonorModel> list;
    private ListView listview;
    private MyAdapter adapter;
    private View rootView;//缓存Fragment view
    private int imgW = 0;
    private boolean isGetting = false;
    private ImageView no_data_img;
    private RefreshLayout mRefreshLayout;

    private void calculateImageWidth(){
        int width = ScreenUtils.getScreenWidth(getActivity());
        float density = ScreenUtils.getScreenDensity(getActivity());
        imgW = (int) ((width-50*density)/linecount);
    }

    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        calculateImageWidth();
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        if (rootView == null) {
            rootView = inflater.inflate(R.layout.lang_honor_layout, container, false);
            pageindex = 0;
            if (list == null){
                list = new ArrayList<LangHonorModel>();
                int width = ScreenUtils.getScreenWidth(getActivity());
                float density = ScreenUtils.getScreenDensity(getActivity());
                imgW = (int) ((width-50*density)/linecount);
            }
            no_data_img = (ImageView)rootView.findViewById(R.id.no_data_img);
            listview=(ListView) rootView.findViewById(R.id.honor_lang_listview);
            adapter=new MyAdapter();
            listview.setAdapter(adapter);
            listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
                @Override
                public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                    Log.e("TAG","position="+position);
                }
            });

            mRefreshLayout = rootView.findViewById(R.id.refreshLayout);
            //设置 Header 为 贝塞尔雷达 样式
            mRefreshLayout.setRefreshHeader(new BezierRadarHeader(getActivity()).setEnableHorizontalDrag(true));//BezierRadarHeader
            //设置 Footer 为 球脉冲 样式
            mRefreshLayout.setRefreshFooter(new ClassicsFooter(getActivity()).setSpinnerStyle(SpinnerStyle.FixedBehind));//BallPulseFooter ClassicsFooter
            mRefreshLayout.setPrimaryColors(AppThemeUtils.getInstance().getRefreshBackgroundColor(),AppThemeUtils.getInstance().getRefreshAccessColor());
            mRefreshLayout.setEnableRefresh(true);//启用刷新
            mRefreshLayout.setEnableLoadMore(true);//启用加载
            //刷新
            mRefreshLayout.setOnRefreshListener(new OnRefreshListener() {
                @Override
                public void onRefresh(RefreshLayout refreshlayout) {
                    //refreshlayout.finishRefresh();
                    pageindex = 0;
                    getData();
                }
            });
            mRefreshLayout.setOnLoadMoreListener(new OnLoadMoreListener() {
                @Override
                public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                    //refreshLayout.finishLoadMore();
                    getData();
                }
            });

            RelativeLayout lang_honor = (RelativeLayout) rootView.findViewById(R.id.lang_honor);
            lang_honor.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());
            listview.setDivider(new ColorDrawable(AppThemeUtils.getInstance().getMainColor()));
            listview.setDividerHeight(ScreenUtils.dip2px(getActivity(), 1));

            getData();
        }else {
            //缓存的rootView需要判断是否已经被加过parent， 如果有parent需要从parent删除，要不然会发生这个rootview已经有parent的错误。
            ViewGroup parent = (ViewGroup) rootView.getParent();
            if (parent != null) {
                parent.removeView(rootView);
            }
        }

        return rootView;
    }

    public void getFirstData(boolean isFirst){
        if (listview == null || list == null){
            return;
        }
        if (list.size() == 0){
            //listview.startRefresh();
            if (mRefreshLayout != null){
                pageindex = 0;
                mRefreshLayout.autoRefresh();
            }
        }else {
            if (isFirst == true){
                //listview.smoothScrollToPosition(0);
                listview.setSelection(0);
            }
        }
    }

    private void getData(){
        if (listview == null){
            return;
        }
        if (isGetting == true){
            return;
        }
        isGetting = true;

        new Thread(){
            @Override
            public void run() {
                super.run();
                final HashMap<String, String> map = new HashMap<String, String>();
                if (CommonUtils.isEmpty(userid)){
                    map.put(APIKey.tokenKey, CommonUtils.formatString(CustomApplication.loginModel.getToken()));
                }else {
                    map.put(APIKey.useridKey,userid);
                }
                map.put("pageIndex",pageindex+"");
                map.put("pageRecord",Records+"");
                HttpsUtils.miniAppDo(map, "miniapp/langappid/userhonorlist.do", new HttpCallBack() {
                    @Override
                    public void onSuccess(String data) {
                        isGetting = false;
                        if (getActivity() != null){

                            CommonModel commonModel = GsonTools.getCommonModel(data);
                            if (commonModel.getFlag().equals("1")){
                                List<LangHonorModel> l = GsonTools.getLangHonorModel(data);
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mRefreshLayout.getState() == RefreshState.Loading){
                                            //listview.stopLoadMore();
                                            mRefreshLayout.finishLoadMore();
                                        }else {
                                            list.clear();
                                            //listview.stopRefresh(true);
                                            mRefreshLayout.finishRefresh();
                                        }
                                        if (l != null && l.size() > 0){
                                            no_data_img.setVisibility(View.INVISIBLE);
                                            if (l.size() >= Records){
                                                //listview.setPullLoadEnable(true);
                                                mRefreshLayout.setEnableLoadMore(true);
                                            }else {
                                                //listview.setPullLoadEnable(false);
                                                mRefreshLayout.setEnableLoadMore(false);
                                            }
                                            list.addAll(l);
                                        }else {
                                            isHasMore = false;
                                            //listview.setPullLoadEnable(false);
                                            mRefreshLayout.setEnableLoadMore(false);
                                        }
                                        adapter.notifyDataSetChanged();
                                        if (pageindex == 0){
                                            //listview.smoothScrollToPosition(0);
                                            listview.setSelection(0);
                                        }
                                        pageindex += 1;
                                    }
                                });
                            }else {
                                getActivity().runOnUiThread(new Runnable() {
                                    @Override
                                    public void run() {
                                        if (mRefreshLayout.getState() == RefreshState.Loading){
                                            //listview.stopLoadMore();
                                            mRefreshLayout.finishLoadMore();
                                        }else {
                                            list.clear();
                                            //listview.stopRefresh(true);
                                            mRefreshLayout.finishRefresh();
                                        }
                                        CustomApplication.showTip(commonModel, getActivity());
                                    }
                                });
                            }

                        }
                    }

                    @Override
                    public void onError(String msg) {
                        isGetting = false;
                        if (getActivity() != null){
                            getActivity().runOnUiThread(new Runnable() {
                                @Override
                                public void run() {
                                    if (mRefreshLayout.getState() == RefreshState.Loading){
                                        mRefreshLayout.finishLoadMore();
                                    }else {
                                        mRefreshLayout.finishRefresh();
                                    }
                                }
                            });
                        }
                    }
                });
            }
        }.start();

    }

    private class MyAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            // TODO Auto-generated method stub
            int count = list.size()/linecount;
            if (list.size()%linecount > 0){
                count += 1;
            }
            return count;
        }


        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return list.get(position);
        }

        @Override
        public long getItemId(int position) {
            // TODO Auto-generated method stub
            return position;
        }

        @Override
        public boolean isEnabled(int position) {
            // TODO Auto-generated method stub
            return super.isEnabled(position);
        }

        /**
         * @param position
         * @param convertView
         * @param parent
         * @return
         */
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub
            //convertView的复用
            if (convertView == null) {
                convertView = View.inflate(getActivity(), R.layout.honor_listview_item,null);
            }
            View view=convertView;

            LinearLayout honor_listview_item = (LinearLayout) view.findViewById(R.id.honor_listview_item);
            honor_listview_item.setBackgroundColor(AppThemeUtils.getInstance().getMainColor());

            //view = LayoutInflater.from(getActivity()).inflate(R.layout.honor_listview_item, null);
            LinearLayout honor_lang_1 = (LinearLayout) view.findViewById(R.id.honor_lang_1);
            LinearLayout honor_lang_2 = (LinearLayout) view.findViewById(R.id.honor_lang_2);
            LinearLayout honor_lang_3 = (LinearLayout) view.findViewById(R.id.honor_lang_3);
            LinearLayout honor_lang_4 = (LinearLayout) view.findViewById(R.id.honor_lang_4);
            ImageView honor_lang_img1 = (ImageView) view.findViewById(R.id.honor_lang_img1);
            TextView honor_lang_text1 = (TextView) view.findViewById(R.id.honor_lang_text1);
            ImageView honor_lang_img2 = (ImageView) view.findViewById(R.id.honor_lang_img2);
            TextView honor_lang_text2 = (TextView) view.findViewById(R.id.honor_lang_text2);
            ImageView honor_lang_img3 = (ImageView) view.findViewById(R.id.honor_lang_img3);
            TextView honor_lang_text3 = (TextView) view.findViewById(R.id.honor_lang_text3);
            ImageView honor_lang_img4 = (ImageView) view.findViewById(R.id.honor_lang_img4);
            TextView honor_lang_text4 = (TextView) view.findViewById(R.id.honor_lang_text4);

            honor_lang_img1.setVisibility(View.GONE);
            honor_lang_text1.setVisibility(View.GONE);
            honor_lang_img2.setVisibility(View.GONE);
            honor_lang_text2.setVisibility(View.GONE);
            honor_lang_img3.setVisibility(View.GONE);
            honor_lang_text3.setVisibility(View.GONE);
            honor_lang_img4.setVisibility(View.GONE);
            honor_lang_text4.setVisibility(View.GONE);

            honor_lang_text1.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            honor_lang_text2.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            honor_lang_text3.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());
            honor_lang_text4.setTextColor(AppThemeUtils.getInstance().getTextColorOfWeiJu());

            int num = 0;
            int count = linecount*position;
            if (list.size()-count >= linecount){
                num = linecount;
            }else {
                while (list.size()-count > 0){
                    num+=1;
                    count+=1;
                }
            }
            int index = linecount*position;
            for (int i = 0; i < num; i++){
                LangHonorModel model = list.get(index+i);
                if (i == 0){
                    honor_lang_img1.setVisibility(View.VISIBLE);
                    honor_lang_text1.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = honor_lang_img1.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    honor_lang_img1.setLayoutParams(params);
                    params = honor_lang_text1.getLayoutParams();
                    params.width = imgW;
                    honor_lang_text1.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getImg()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(honor_lang_img1);
                    honor_lang_text1.setText(model.getName());
                    honor_lang_1.setTag(index+i);
                    honor_lang_1.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }else if (i == 1){
                    honor_lang_img2.setVisibility(View.VISIBLE);
                    honor_lang_text2.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = honor_lang_img2.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    honor_lang_img2.setLayoutParams(params);
                    params = honor_lang_text2.getLayoutParams();
                    params.width = imgW;
                    honor_lang_text2.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getImg()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(honor_lang_img2);
                    honor_lang_text2.setText(model.getName());
                    honor_lang_2.setTag(index+i);
                    honor_lang_2.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }else if (i == 2){
                    honor_lang_img3.setVisibility(View.VISIBLE);
                    honor_lang_text3.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = honor_lang_img2.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    honor_lang_img3.setLayoutParams(params);
                    params = honor_lang_text3.getLayoutParams();
                    params.width = imgW;
                    honor_lang_text3.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getImg()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(honor_lang_img3);
                    honor_lang_text3.setText(model.getName());
                    honor_lang_3.setTag(index+i);
                    honor_lang_3.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }else if (i == 3){
                    honor_lang_img4.setVisibility(View.VISIBLE);
                    honor_lang_text4.setVisibility(View.VISIBLE);
                    ViewGroup.LayoutParams params = honor_lang_img4.getLayoutParams();
                    params.width =imgW;
                    params.height = imgW;
                    honor_lang_img4.setLayoutParams(params);
                    params = honor_lang_text4.getLayoutParams();
                    params.width = imgW;
                    honor_lang_text4.setLayoutParams(params);
                    Glide.with(getActivity()).load(model.getImg()).placeholder(AppThemeUtils.getInstance().getDefaultImageBg()).dontAnimate().into(honor_lang_img4);
                    honor_lang_text4.setText(model.getName());
                    honor_lang_4.setTag(index+i);
                    honor_lang_4.setOnClickListener(new View.OnClickListener() {
                        @Override
                        public void onClick(View v) {
                            onClickItem(v);
                        }
                    });
                }
            }
            return view;
        }
    }

    private void onClickItem(View v){
        LangHonorModel model = list.get((int)v.getTag());
        CustomDialog dialog = null;
        final CustomDialog.Builder builder = new CustomDialog.Builder(getActivity());
        builder.setTitle(model.getName());
        builder.setMessage(model.getDetail());
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        });
        dialog = builder.create();
        dialog.show();
    }

}
